package net.zjitc.controller;

import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import net.zjitc.common.R;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    private final String basePath = System.getProperty("user.dir") + "/src/main/resources/img/";
    //文件上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //file是⼀个临时⽂件，需要转存到指定位置，否则本次请求完成后临时⽂件会删除
        log.info(file.toString());
        //原始⽂件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使⽤UUID重新⽣成⽂件名，防⽌⽂件名称重复造成⽂件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;
        //创建⼀个⽬录对象
        File dir = new File(basePath+fileName);
        //判断当前⽬录是否存在
        if (!dir.exists()) {
            //⽬录不存在，需要创建
            dir.mkdirs();
        }
        try {
            //将临时⽂件转存到指定位置
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }
    //文件下载
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //输⼊流，通过输⼊流读取⽂件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //输出流，通过输出流将⽂件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            String s = name.split("\\.")[1];
            response.setContentType("image/"+s);
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

